<template>
  <div class="keForm">
    <a-form :form="formData">
      <a-row v-for="(item, index) in formItems2" :key="index">
        <a-col v-bind="colLayout">
          <a-form-item :label="item.label" :label-col="labelCol" :wrapper-col="wrapperCol">
            <template v-if="item.type === 'password'">
              <a-input-password
                :placeholder="item.placeholder"
                v-decorator="[item.field, { rules: item.rules }]"
                v-bind="item.otherOptions"
                allowClear
              />
            </template>
            <template v-else-if="item.type === 'input' && item.field !== 'items'">
              <a-input
                @click="openDialog(item.field)"
                :placeholder="item.placeholder"
                v-bind="item.otherOptions"
                v-decorator="[item.field, { rules: item.rules }]"
                allowClear
              />
            </template>
            <template v-else-if="item.type === 'input' && item.field === 'items'">
              <div v-for="(correct, index6) in item.options" style="display: flex;" :key="index6">
                <a-input
                  @click="openDialog(correct.fieldTwo)"
                  :placeholder="item.placeholder"
                  v-bind="item.otherOptions"
                  style="margin-right: 15px;margin-top: 5px;"
                  v-decorator="[correct.fieldTwo, { rules: item.rules }]"
                >
                </a-input>
                <a-form-item>
                  <a-input-number
                    :placeholder="item.placeholder"
                    v-bind="item.otherOptions"
                    @change="scoreChange"
                    :min="1"
                    v-decorator="[correct.fieldThree, { rules: item.rules }]"
                  />
                </a-form-item>
              </div>
            </template>
            <template v-else-if="item.type === 'textarea'">
              <a-textarea
                :placeholder="item.placeholder"
                v-bind="item.otherOptions"
                v-decorator="[item.field, { rules: item.rules }]"
                allowClear
              />
            </template>
            <template v-else-if="item.type === 'numberInput'">
              <a-input-number
                :placeholder="item.placeholder"
                :disabled="questionType === 4"
                v-bind="item.otherOptions"
                v-decorator="[item.field, { rules: item.rules }]"
              />
            </template>
            <template v-else-if="item.type === 'select'">
              <a-select
                :placeholder="item.placeholder"
                v-bind="item.otherOptions"
                v-decorator="[item.field, { rules: item.rules }]"
                style="width: 100%;"
              >
                <a-select-option v-for="(option, index2) in item.options" :key="index2" :value="option.value">
                  {{ option.label }}
                </a-select-option>
              </a-select>
            </template>
            <template v-else-if="item.type === 'radio'">
              <a-radio-group v-bind="item.otherOptions" v-decorator="[item.field, { rules: item.rules }]">
                <a-radio v-for="(radioOption, index3) in item.options" :key="index3" :value="radioOption.value">
                  {{ radioOption.label }}
                </a-radio>
              </a-radio-group>
            </template>

            <template v-else-if="item.type === 'checkbox'">
              <a-checkbox-group v-bind="item.otherOptions" v-decorator="[item.field, { rules: item.rules }]">
                <a-checkbox
                  v-for="(checkBoxOption, index4) in item.options"
                  :key="index4"
                  :value="checkBoxOption.value"
                >
                  {{ checkBoxOption.label }}
                </a-checkbox>
              </a-checkbox-group>
            </template>
            <template v-if="item.type === 'rate'">
              <a-rate
                :placeholder="item.placeholder"
                v-bind="item.otherOptions"
                v-decorator="[item.field, { rules: item.rules }]"
              />
            </template>
            <template v-if="item.type === 'addQuestion'">
              <div v-for="(question, index5) in item.options" :key="index5" style="display: flex;">
                <span>{{ question.value }}</span>
                <a-form-item>
                  <a-input
                    :placeholder="item.placeholder"
                    style="width: 50px;margin: 0 20px;"
                    @change="optionsChange($event, index, index5)"
                    v-bind="item.otherOptions"
                    v-decorator="[question.field, { rules: item.rules, initialValue: question.value }]"
                  ></a-input>
                </a-form-item>
                <a-form-item>
                  <a-input
                    :placeholder="item.placeholder"
                    @click="openDialog(question.fieldTwo)"
                    v-bind="item.otherOptions"
                    v-decorator="[
                      question.fieldTwo,
                      { rules: item.rules, initialValue: question.valueTwo ? question.valueTwo : '' }
                    ]"
                  ></a-input>
                </a-form-item>
                <template v-if="!item.NoDeleteBtn">
                  <a-button
                    type="danger"
                    icon="delete"
                    style="width: 50px;margin-left: 20px;margin-top: 4px;"
                    @click="deleteQuestion(index, index5)"
                  />
                </template>
              </div>
            </template>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <j-modal :visible="modalVisible" centered :width="1200" @ok="handleOk" @cancel="handleCancel">
      <div style="padding:15px;">
        <wangEditor :htmlTwo="html" @contentChange="contentChange"></wangEditor>
      </div>
    </j-modal>
    <template v-if="needFooter">
      <a-button type="primary" class="footerBtn" @click="submitForm">
        提交
      </a-button>
      <a-button class="footerBtn" @click="resetForm">重置</a-button>
      <template v-if="addChooseBtn">
        <a-button
          class="footerBtn"
          style="background-color: #13ce66;color: white;border: none !important;"
          @click="addQuestion"
        >
          添加选项
        </a-button>
      </template>

      <a-button
        class="footerBtn"
        style="background-color: #13ce66;color: white;border: none !important;"
        @click="previewQuestion"
      >
        预览
      </a-button>
      <j-modal
        :visible="previewModalVisible"
        centered
        :width="1200"
        destroyOnClose
        :footer="null"
        @cancel="previewModalVisible = false"
      >
        <div id="previewTitle"></div>
        <template v-if="previewOption.length > 0">
          <div v-for="(previewOption, index6) in previewOption" :key="index6" style="display: flex">
            <span>{{ previewOption.value }}.</span>
            <div class="previewOptionValue"></div>
          </div>
        </template>
      </j-modal>
    </template>
  </div>
</template>

<script>
import { createQuestion } from '@/api/oesQuestion.js'
import wangEditor from '@/components/wangEditor/wangEditor.vue'
export default {
  name: 'keForm',
  components: { wangEditor },
  props: {
    formItems: {
      type: Array,
      require: true
    },
    needFooter: {
      type: Boolean,
      default: true
    },
    config: {
      type: Array,
      default: () => []
    },
    //填空题分数对象 针对填空题
    score: {},
    addChooseBtn: {
      type: Boolean,
      default: true
    },
    colLayout: {
      type: Object,
      default: () => ({
        xl: 6, // >1920px 4个
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24
      })
    },
    labelCol: {
      type: Object,
      default: () => ({
        xs: { span: 24 },
        sm: { span: 1 }
      })
    },
    questionType: {
      type: Number,
      required: true
    },
    wrapperCol: {
      type: Object,
      default: () => ({
        xs: { span: 24 },
        sm: { span: 8 }
      })
    }
  },
  data() {
    return {
      modalVisible: false,
      previewModalVisible: false,
      toolbarConfig: {},
      inputHtmlValue: '',
      editId: null,
      formHtmlvalue: {},
      previewOption: [],
      optionsMax: 4,
      correctArrayIndex: 1,
      // 默认填空个数
      defaultBlank: 0,
      formItems2: [...this.formItems, ...this.config],
      currentInput: null,
      html: '',
      wangEditorContent: {},
      mode: 'default', // or 'simple'
      formData: this.$form.createForm(this, { name: 'basicForm' })
    }
  },
  methods: {
    // 填空分数改变
    scoreChange() {
      this.$nextTick(() => {
        let total = 0
        const formData = this.formData.getFieldsValue()
        for (let i = 1; i <= (this.defaultBlank === 0 ? 1 : this.defaultBlank); i++) {
          total = total + formData[`srore${i}`]
        }
        this.formData.setFieldsValue({
          score: total
        })
      })
    },
    previewQuestion() {
      const questionIndex = this.getQuestionIndex()
      console.log(this.formItems2[questionIndex], this.formHtmlvalue, 8888)
      this.previewOption = this.formItems2[questionIndex] ? this.formItems2[questionIndex].options : []

      this.previewModalVisible = true
      this.$nextTick(() => {
        const previewTitle = this.formHtmlvalue.title ? this.formHtmlvalue.title : ''
        const previewTitleEle = document.getElementById('previewTitle')
        if (this.previewOption.length > 0) {
          const previewOptionValueEle = document.querySelectorAll('.previewOptionValue')
          previewOptionValueEle.forEach((e, index) => {
            e.innerHTML = this.formHtmlvalue[`${this.previewOption[index].fieldTwo}`]
              ? this.formHtmlvalue[`${this.previewOption[index].fieldTwo}`]
              : ''
          })
        }
        previewTitleEle.innerHTML = previewTitle
      })
    },
    submitForm() {
      this.formData.validateFields(async err => {
        if (err) {
          return this.$message.error('请填写完整信息')
        } else {
          // <input data-w-e-type=\"fill-blank\" width=\"80px\" index=\"0\"/>
          //   const reg = /<input data-w-e-type=\\"fill-blank\\" width=\\".*px\\" index=\\".*\\"\/>/
          //   console.log(this.formHtmlvalue)
          // if (this.questionType === 4 && reg.test(this.formHtmlvalue.title) ) {
          //   return this.$message.error('检测到填空题并未有填空,请核对题干！')
          // }
          const formData = this.formData.getFieldsValue()
          const items = []
          const itemIndex = this.formItems2.findIndex(item => {
            return item.field === 'items'
          })
          if (!!this.formItems2[itemIndex]) {
            this.formItems2[itemIndex].options.forEach(e => {
              items.push({
                prefix: formData[`${e.field}`],
                srore: formData[`${e.fieldThree}`],
                content: formData[`${e.fieldTwo}`]
              })
            })
          }
          const res = await createQuestion({
            questionType: this.questionType,
            id: this.editId,
            ...formData,
            ...this.formHtmlvalue,
            correct: formData.correct ? formData.correct : formData.correctArray,
            items
          })
          if (res.code !== 200) {
            return this.$message.error('服务器错误')
          } else {
            this.$message.success('添加成功')
          }

          this.resetForm()
        }
      })
    },
    optionsChange(e, id, index) {
      const radioIndex = this.getRadioIndex()
      this.formItems2[id].options[index].value = e.target.value
      this.formItems2[radioIndex].options[index].label = e.target.value
    },
    resetForm() {
      if (this.questionType === 4) {
        const index = this.getCompleCArrIndex()
        this.formItems2[index].options = {}
      }
      for (let key in this.formHtmlvalue) {
        this.formHtmlvalue[key] = ''
      }
      this.formData.resetFields()
    },
    getQuestionIndex() {
      const index = this.formItems2.findIndex(item => {
        return item.type === 'addQuestion'
      })
      return index
    },
    getCompleCArrIndex() {
      const index = this.formItems2.findIndex(item => {
        return item.type === 'input' && item.field === 'items'
      })
      return index
    },
    getRadioIndex() {
      const radioIndex = this.formItems2.findIndex(item => {
        return item.type === 'radio' || item.type === 'checkbox'
      })
      return radioIndex
    },
    // 删除问题
    deleteQuestion(id, index) {
      const radioIndex = this.getRadioIndex()
      this.formItems2[id].options.splice(index, 1)
      this.formItems2[radioIndex].options.splice(index, 1)
    },
    addQuestion() {
      const radioIndex = this.getRadioIndex()
      const questionIndex = this.getQuestionIndex()
      this.optionsMax++
      // 最后一个选项的值
      const lastLabel = this.formItems2[questionIndex].options[this.formItems2[questionIndex].options.length - 1].value
      // 下一次选项的值
      const nextLabel = String.fromCharCode(lastLabel.charCodeAt() + 1)
      this.formItems2[questionIndex].options.push({
        field: 'prefix' + this.optionsMax,
        fieldTwo: 'content' + this.optionsMax,
        value: nextLabel
      })
      this.formItems2[radioIndex].options.push({
        label: nextLabel,
        value: nextLabel
      })
    },
    // wangeditor
    contentChange(val, val2) {
      this.wangEditorContent = {
        html: val,
        text: val2
      }
    },
    //
    openDialog(currentInput) {
      this.currentInput = currentInput
      this.inputHtmlValue = this.formHtmlvalue[`${this.currentInput}`]
        ? this.formHtmlvalue[`${this.currentInput}`]
        : this.formData.getFieldValue(currentInput)
      console.log(this.currentInput)
      this.html = this.inputHtmlValue
      this.modalVisible = true
    },
    handleCancel() {
      this.html = ''
      this.modalVisible = false
    },
    handleOk() {
      this.formData.setFieldsValue({
        [this.currentInput]: this.wangEditorContent.text
      })
      // 如果是填空题的情况
      if (this.questionType === 4 && this.currentInput === 'title') {
        const reg = /<input data-w-e-type=\"fill-blank\" width=\".*px\" index=\".*\"\/>/
        console.log(this.wangEditorContent.html.match(reg))
        this.defaultBlank = this.wangEditorContent.html.match(reg)
          ? this.wangEditorContent.html.match(reg)[0].split('fill-blank').length - 1
          : 0
        if (this.defaultBlank !== 0) {
          const correctArrIndex = this.getCompleCArrIndex()
          const optionArr = []
          for (let i = 1; i <= this.defaultBlank; i++) {
            optionArr.push({
              fieldTwo: 'content' + i,
              fieldThree: 'srore' + i
            })
          }
          this.formItems2[correctArrIndex].options = optionArr
        }
      }
      this.formHtmlvalue[`${this.currentInput}`] = this.wangEditorContent.html
      this.html = ''
      this.modalVisible = false
    }
  },
  created() {
    if (this.$route.query.data && typeof this.$route.query.data !== 'string') {
      this.editId = this.$route.query.data.id
      const items = this.formItems2.find(item => {
        return item.field === 'items'
      })
      items.options = this.$route.query.data.items.map((item, index) => {
        return {
          field: 'prefix' + (index + 1),
          fieldTwo: 'content' + (index + 1),
          fieldThree: 'srore' + (index + 1),
          value: item.prefix
        }
      })
    }
  },
  mounted() {
    if (!!this.$route.query.data && typeof this.$route.query.data !== 'string') {
      const formData = this.formData.getFieldsValue()
      for (let key in this.$route.query.data) {
        if (key in formData) {
          let item = this.$route.query.data[key]
          if (typeof this.$route.query.data[key] === 'string') {
            item = this.$route.query.data[key].replace(/<\/?.+?>/g, '')
            item = item.replace('&nbsp;', ' ')
          }
          if (typeof item === 'string') {
            if (key === 'correct' && item.search(',') !== -1) {
              item = item.split(',')
            }
          }

          this.formHtmlvalue[key] = this.$route.query.data[key]

          this.formData.setFieldsValue({
            [key]: item
          })
        }
      }
      const index = this.getQuestionIndex()
      if (this.formItems2[index]) {
        this.formItems2[index].options.forEach(e => {
          this.formHtmlvalue[`${e.fieldTwo}`] = e.valueTwo ? e.valueTwo : ''
        })
      }
      this.$route.query.data.items.forEach((item, index) => {
        this.formHtmlvalue[`content${index + 1}`] = item.content
        for (let key in item) {
          if (key + (index + 1) in formData) {
            this.formData.setFieldsValue({
              [key + (index + 1)]: item[key].replace(/<\/?.+?>/g, '').replace(/&nbsp;/g, ' ')
            })
          }
        }
      })
    }
  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped>
.footerBtn {
  margin: 0 10px;
}
.previewOptionValue {
  padding-left: 6px;
}
/* 富文本编辑器 */
::v-deep .w-e-full-screen-container {
  z-index: 999 !important;
}
#previewTitle >>> input {
  border: none;
  border-bottom: 1px solid red;
}
</style>
